package ths

import (
	"fmt"
	s "gitee.com/gcom/stockdock/core/support"
	"gitee.com/gcom/stockdock/spider/ths"
	"time"
)

// 更新同花顺股票列表
func UpdateStockListThs(ctx s.TracerCtx) {
	var ch = make(chan ths.QuotePageEventThs)
	var err error
	defer close(ch)
	go func() {
		err = ths.ListDailyQuoteThs(ctx, ch)
	}()

	var pageNo, pageCount, total = 1, 1, 0
	var entities = make([]*ths.StockThsEntity, 0, 200)
	for ; pageNo <= pageCount; pageNo++ {
		var page = <-ch
		if page.Err != nil {
			s.WriteErrEvent(ctx, "获取股票行情异常", page.Err)
			return
		}

		if pageCount < page.PageCount {
			pageCount = page.PageCount
		}
		s.WriteEvent(ctx, fmt.Sprintf("[%d/%d]成功获取股票行情%d条", pageNo, pageCount, len(page.Data)))

		for _, v := range page.Data {
			entities = append(entities, &ths.StockThsEntity{DailyQuoteThs: v})
		}
		if len(entities) >= 200 || (pageNo == pageCount && len(entities) > 0) {
			_, e := ths.UpdateStockThsQuote(ctx.DB, entities)
			if e != nil {
				s.WriteErrEvent(ctx, "写入股票行情异常", e)
				return
			}
			total += len(entities)
			entities = entities[:0]
		}

		time.Sleep(1 * time.Second)
	}

	if err != nil {
		s.WriteErrEvent(ctx, "获取股票行情异常", err)
		return
	}
	s.WriteEvent(ctx, fmt.Sprintf("完成股票行情更新，共%d条", total))
}
